﻿using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Linq;
using System.Net.Http;
using Systen.Core.DTO;
using Systen.Core.Tool;
using Systen.Shop.Members.Models;
using Systen.Wechat.Logins;
using Systen.Wechat.Logins.Models;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using WalkingTec.Mvvm.Mvc;

namespace DaiMaoSource.Controllers
{
    [ActionDescription("用户管理")]
    [ApiController]
    [Route("api/v1/Wechat")]
    public class WechatLoginApiController : BaseApiController
    {
        //小程序授权登录
        [HttpPost("WechatJSAPILogin")]
        public OperationResult WechatJSAPILogin(LoginCode loginCode)
        {
            var result = new OperationResult()
            {
                StatusCode = OperationResultStatus.Error,
                Message = "你已取消授权!"
            };
            if (string.IsNullOrEmpty(loginCode.code))
            {
                result.Message = "code值不能为空";
                return result;
            }
            var appid = Config.app_id;
            var secret = Config.app_secret;
            var js_code = loginCode.code;
            var grant_type = "authorization_code";
            if (string.IsNullOrEmpty(appid))
            {
                result.Message = "appid配置错误";
                return result;
            }
            if (string.IsNullOrEmpty(secret))
            {
                result.Message = "secret配置错误";
                return result;
            }
            string wechatUrl = $"https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={loginCode.code}&grant_type={grant_type}";
            HttpClient client = new HttpClient();
            var strWechatReturn = client.GetStringAsync(wechatUrl).Result;
            Hashtable wechatReturn = JsonConvert.DeserializeObject<Hashtable>(strWechatReturn);

            if (strWechatReturn.Contains("errcode"))
            {
                result.Message = "错误码:" + wechatReturn["errcode"].ToString() + " 错误信息:" + wechatReturn["errmsg"].ToString();
                return result;
            }
            //系统内查询
            Member memberInfo = DC.Set<Member>()
                   .CheckEqual(wechatReturn["openid"].ToString(), x => x.OpenId)
                   //.CheckEqual(wechatReturn["unionid"].ToString(), x => x.UnionId)
                   .CheckEqual(true, x => x.IsValid).FirstOrDefault();
            string LoginToken = "";
            DateTime dtNow = DateTime.Now;
            try
            {
                if (memberInfo != null)
                {
                    if (memberInfo.Disabled == true)
                    {
                        result.Message = "账号已禁用";
                        return result;
                    }
                    //修改登录时间 保存令牌
                    memberInfo.LastLoginDate = dtNow;
                    memberInfo.LoginTokenTime = dtNow;
                    memberInfo.LoginToken = Tool.GetToken(memberInfo.UserName, memberInfo.LoginTokenTime.Value, Guid.NewGuid().ToString("N"));
                    //DC.Set<Member>().Update(memberInfo);
                    DC.UpdateProperty(memberInfo, "LastLoginDate");
                    DC.UpdateProperty(memberInfo, "LoginTokenTime");
                    DC.UpdateProperty(memberInfo, "LoginToken");
                    LoginToken = memberInfo.LoginToken;
                }
                else
                {
                    //创建账户
                    Member newMember = new Member()
                    {
                        UserName = wechatReturn["openid"].ToString(),
                        Disabled = false,
                        IsEmailAuthen = false,
                        IsPhoneAuthen = false,
                        IsRealNameAuthen = false,
                        OrderNumber = 0,
                        PlatformAccessType = 1,
                        Sex = 0,
                        OpenId = wechatReturn["openid"].ToString(),
                        CreateBy = "WechatJSAPI",
                        CreateTime = dtNow,
                        Nick = loginCode.nick,
                        Photo = loginCode.photo,
                        EntryTime = dtNow,
                        //UnionId = wechatReturn["unionid"].ToString(),
                    };
                    newMember.LastLoginDate = dtNow;
                    newMember.LoginTokenTime = dtNow;
                    newMember.LoginToken = Tool.GetToken(newMember.UserName, newMember.LoginTokenTime.Value, Guid.NewGuid().ToString("N"));
                    //添加到数据库
                    DC.Set<Member>().Add(newMember);
                    LoginToken = newMember.LoginToken;
                }
                DC.SaveChanges();
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
                return result;
            }
            var userCookie = new
            {
                LoginToken,
            };

            //用户信息存cookies
            var jsonData = JsonConvert.SerializeObject(userCookie);
            HttpContext.Response.Cookies.Append("memberInfo", jsonData);

            result.StatusCode = OperationResultStatus.Success;
            result.Message = "ok";
            return result;
        }



        //测试用
        [HttpGet("Ceshi")]
        public string Ceshi(Guid loginCode)
        {
            Member memberInfo = DC.Set<Member>()
                   .CheckEqual(loginCode, x => x.ID).FirstOrDefault();
            memberInfo.LastLoginDate = DateTime.Now;
            //DC.UpdateEntity<Member>(memberInfo);
            //DC.Entry(memberInfo).Property("CreateDate").IsModified = false;
            // DC.Set<Member>().Update(memberInfo);
            //DC.Set<Member>().Attach(memberInfo);
            //DC.Set<Member>().entry
            //memberInfo.Property("LastLoginDate").IsModified = true;
            //memberInfo.LastLoginDate.
            //DC.UpdateProperty<Member>(memberInfo, "LastLoginDate");
            //using (DataContext dc =new )
            //{ 

            //}
            //DC.RunSQL("update ShopMembers_Member set LastLoginDate = '" + DateTime.Now.ToString() + "' where ID='" + memberInfo.ID + "'");
            DC.SaveChanges();

            return "";
        }

        //测试用
        [HttpGet("Ceshi1")]
        public string Ceshi1(string xxx)
        {
            return Tool.MD5Pwd(xxx.Trim());
        }


    }
}
